package com.itwang.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itwang.entity.User;
import com.itwang.entity.dto.UserLoginDTO;
import com.itwang.entity.dto.UserTokenDTO;
import com.itwang.service.IUserService;
import com.itwang.utils.AjaxResult;

import com.itwang.utils.jwt.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.tomcat.util.descriptor.InputSourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {

    @Resource
    IUserService userService;

    @Resource
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody UserLoginDTO loginDto, HttpServletResponse response) {
        UserTokenDTO dto = new UserTokenDTO();
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUserName()));
        Assert.notNull(user, "用户不存在");

        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassWord()))){
            return AjaxResult.error("密码不正确");
        }

        System.out.println("user:"+user);

        String jwt =jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return AjaxResult.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public AjaxResult logout() {
        SecurityUtils.getSubject().logout();
        return AjaxResult.success(null);
    }

}